let tableIns;
let tree;
let startDateIns;
let endDateIns;
layui.use(['element', 'form', 'table', 'layer', 'laydate', 'tree', 'util'], function () {
    let table = layui.table;
    let form = layui.form;//select、单选、复选等依赖form
    let element = layui.element; //导航的hover效果、二级菜单等功能，需要依赖element模块
    let laydate = layui.laydate;
    tree = layui.tree;
    var $=layui.jquery;
    let height = document.documentElement.clientHeight - 60;
    
    $.post('/platform/grant/findByTime', {}, function (data) {
        var $html = "";
        if(data.data != null){
            $.each(data.data, function (index, item) {
            	$html += "<option value='" + item.time + "'>" + item.time + "</option>";
            });
            $("select[name='time']").append($html);
            form.render('select');
        }
    });

    tableIns = table.render({
        elem: '#quarterListTable'
        , url: ctx + '/platform/grant/queryByNames'
        , method: 'GET'
        //请求前参数处理
        , where: {
            time: ""
        }
        , response: {
            statusName: 'flag' //规定数据状态的字段名称，默认：code
            , statusCode: true //规定成功的状态码，默认：0
            , msgName: 'msg' //规定状态信息的字段名称，默认：msg
        }
        //响应后数据处理
        , parseData: function (res) { //res 即为原始返回的数据
            var data = res.data;
            var sum=0;
            var taxSum=0;
            var akm = $("#perAmount").val();
            var geshui=0;
            var hanshui = 0;
            var buhanshui = 0 ;
            var renshu = 0;
            akm=1+akm/100;
            data.forEach(function(item, index){
                sum+=item.payAmount1;
                var taxMoney=0;
                var nottax=0;
                if(parseFloat(item.tax)>0){
                    taxMoney=parseFloat(item.payAmount1)/akm*parseFloat(item.tax)/100;
                }
                
                if(parseFloat(item.payAmount1)>0){
                	nottax=parseFloat(item.payAmount1)/akm;
                }
                item.nottax=nottax.toFixed(2);
                item.ffMoney=taxMoney.toFixed(2);
                taxSum+=taxMoney;
            })
            $.each(data,function(i,obj){
            	
                if(obj.cardCode != null && obj.cardCode != ''){
                	renshu +=1;
                }
                geshui+=parseFloat(obj.ffMoney);
                hanshui += obj.payAmount1;
                buhanshui += parseFloat(obj.nottax);
            });
            $("#sum_money1").html("人数："+renshu);
            $("#sum_money2").html("个税总金额："+formatMoney(geshui));
            $("#sum_money3").html("含税总金额："+formatMoney(hanshui));
            $("#sum_money4").html("不含税总金额："+formatMoney(buhanshui));
            return {
                "flag": res.flag, //解析接口状态
                "msg": res.msg, //解析提示文本
                "data": res.data  //解析数据列表
            };
            
        }
        , toolbar: '#quarterListTableToolbar'
        ,title: '用户个税数据表'
        ,defaultToolbar: ['filter', 'exports', 'print']
        , cols: [[
                  {type:'checkbox'}
            /*{field: 'orderId', width:200, title: '订单号'},*/
             /*{field: 'id',width:200,title: '流水号'}
            , *///{field: 'sellerName',title: '商户名称'}
            , {field: 'personId',title: '服务商名称',hide: true }
            , {field: 'serviceName',title: '服务商名称'}
            , {field: 'payeeName',title: '收款人姓名'}
            , {field: 'cardCode',title: '身份证号'}
            , {field: 'payAmount1',title: '含税金额', align:'right', style:'font-weight:bold'}
            ,{field: 'payAmount',title: '不含税金额', align:'right', style:'font-weight:bold',
                templet: function(d){return formatMoney(d.nottax);}}
            , {field: 'tax',title: '个税征收率', templet: function(d){return d.tax+"%";}}
            , {field: 'payAmount',title: '税额（个税）', align:'right', style:'font-weight:bold',
                templet: function(d){return formatMoney(d.ffMoney);}}
            , {field: 'payAmount',title: '应扣缴税额', align:'right', style:'font-weight:bold',
                templet: function(d){return formatMoney(d.ffMoney);}}
            , {field: 'time', width:180, title: '请求时间'}
           /* , {fixed: 'right', width:100, title: '状态', toolbar: '#quarterListTableBar'}*/
        ]]
       /* , page: true*/
        , height: height
        , cellMinWidth: 80
    });
    

    var $=layui.jquery;
    
    //头工具栏事件
    table.on('toolbar(display)', function (obj) {
    	switch (obj.event) {
    	case 'paymentSel':
    		$('#Btn').addClass("layui-btn-disabled").attr("disabled",true);
    		var checkStatus = table.checkStatus(obj.config.id)
    		,data = checkStatus.data;	// 获取选中的数据
    		var perAmount = $("#perAmount").val();
    	// 获取lay-event对应的值
    	var event = obj.event;
    	// 获取其中选中的主表id
    	
    	var sum=0;
    	layer.msg("加载中,请稍后",{
			icon:16,
			shade: false,
			time:-1
		})
    	
    	if(data.length == 0){
    		layer.msg("请至少选择一条结算项!", {icon: 5});
    		$('#Btn').removeClass("layui-btn-disabled").attr("disabled",false);
    		break;
    	}
    	
    	if(perAmount == '' || perAmount == null){
    		layer.msg("请输入个税百分比!", {icon: 5});
    		$('#Btn').removeClass("layui-btn-disabled").attr("disabled",false);
    		break;
    	}
    	
    	
		
		for(var i = 0; i < data.length; i++){
        	$.ajax({
          url: "/platform/grant/save?cardCode=" + data[i].cardCode + "&time="+data[i].time+"&payAmount1="+data[i].payAmount1+"&nottax="+data[i].nottax+ "&perAmount="
          + perAmount +"&serviceId="+data[i].serviceId +"&sellerId="+data[i].sellerId+"&tax="+data[i].tax+"&ffMoney="+data[i].ffMoney +"&payeeName="+data[i].payeeName + "&provideDetailId=" +data[i].id,
          dataType:'json',
          type:'POST',
          success:function(data){
          	layer.alert(data.responseText, {icon: 1,closeBtn: 0 },
          			function(){
          	window.location.reload();
          	});
          },error:function(data){
          	sum+=1;
          	if(sum == i){
          		layer.alert(data.responseText, {icon: 1,closeBtn: 0 },
              			function(){
              	window.location.reload();
              	});
          	}
          }
      })
    	}
		
    	

    	
            break;
    	
    	case 'setup':
    		layer.open({
                type: 2,
                title: '个税设置',
                closeBtn: 1, //显示关闭按钮
                anim: 2,
                area: ['800px', '450px'],
                shadeClose: true, //开启遮罩关闭
                content: '/platform/grant/settingup',
                success: function(layero, index){

                }
            });
    		break;
    	}
    	
    });
    

    $("#queryBtn,.click_btn").click(function(){
        var time = $("#time").val();
        
        let query = {
            done: function (res, curr, count) {
                //完成后重置where，解决下一次请求携带旧数据
                this.where = {};
            }
        };
        //设定异步数据接口的额外参数
        query.where = {
           time: time};
        //console.info(query.where);
        tableIns.reload(query);

    })


});

function refFormSave(){
	let tax = $("#tax").val();
	if(tax == null || tax == ''){
		layer.msg("请输入新的个税百分比");
		return;
	}
	
	$.ajax({
        url: "/platform/grant/settingup?tax=" + tax ,
        dataType:'json',
        type:'POST',
        success:function(data){
        	layer.alert(data.responseText, {icon: 1,closeBtn: 0 },
        			function(){
        	window.location.reload();
        	layer.closeAll();
        	});
        },error:function(data){
        	layer.alert(data.responseText, {icon: 1,closeBtn: 0 },
        			function(){
        		var index = parent.layer.getFrameIndex(window.name); //先得到当前iframe层的索引
	        	parent.layer.close(index); //再执行关闭
                parent.location.reload();
                $("#perAmount").val(tax);
        	});
        }
    })
	
}


